package com.gmail.andersoninfonet.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.gmail.andersoninfonet.conexao.ConnectionFactory;
import com.gmail.andersoninfonet.modelo.Contato;



public class ContatoDAO {
	private Connection con;
	
	public ContatoDAO(){
		this.con = new ConnectionFactory().getConnection();
	}
	
	
	public void adiciona(Contato contato){
		String sql="insert into contatos" + "(nome,email,endereco,dataNascimento)" + "values (?,?,?,?)";
		try{
			PreparedStatement stmt = con.prepareStatement(sql);
			stmt.setString(1, contato.getNome());
			stmt.setString(2, contato.getEmail());
			stmt.setString(3, contato.getEndereco());
			stmt.setDate(4, new Date(contato.getDataNascimento().getTimeInMillis()));
			
			stmt.execute();
			stmt.close();
			
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
	}
	
	public List<Contato> getLista(){
		String sql="select * from contatos";
		try{
			PreparedStatement stmt = con.prepareStatement(sql);
			ResultSet rs = stmt.executeQuery();
			List<Contato> contatos = new ArrayList<>();
			while(rs.next()){
				Contato contato = new Contato();
				contato.setId(rs.getLong("id"));
				contato.setNome(rs.getString("nome"));
				contato.setEmail(rs.getString("email"));
				contato.setEndereco(rs.getString("endereco"));
				
				Calendar data = Calendar.getInstance();
				data.setTime(rs.getDate("dataNascimento"));
				contato.setDataNascimento(data);
				//SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
				//fmt.format(data);
				contatos.add(contato);
			}
				rs.close();
				stmt.close();
				return   contatos;
			
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
		
		
	} 
	
	public void altera(Contato contato){
		String sql="update contatos set nome=?, email=?," + "endereco=?, dataNascimento=? where id=?";
		try{
			PreparedStatement stmt = con.prepareStatement(sql);
			stmt.setString(1, contato.getNome());
			stmt.setString(2, contato.getEmail());
			stmt.setString(3, contato.getEndereco());
			stmt.setDate(4, new Date(contato.getDataNascimento().getTimeInMillis()));
			stmt.setLong(5, contato.getId());
			
			stmt.execute();
			stmt.close();
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
	}
	
	public void remove(Contato contato){
		String sql = "delete from contatos where id=?";
		try{
			PreparedStatement stmt = con.prepareStatement(sql);
			stmt.setLong(1,	 contato.getId());
			stmt.execute();
			stmt.close();
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
	}
}



